import Vue from 'vue'
export default class WeChatX {
    constructor({App,stateName,stateData}) {
        this.state = stateData;
        this.getApp(App,stateName,stateData);
    }

    getState(){
        return this;
    }

    setState(param){
        let that = this;
        let state = this.state;
        Object.keys(param).some((key)=>{
            if(state[key]){
                that.state[key] = param[key]
            }
        })
    }
    _methods(methods){
        Object.keys(methods).forEach((key)=>{
            Vue.prototype[key] = methods[key];
        })
    }

    getApp(App,stateName,stateData){
            if(App["data"]){
                if(!App["data"][stateName]){
                    let data = App["data"]();
                    data[stateName] = stateData;
                    App["data"] = function () {
                        return data
                    }
                }
            }else {
                App["data"] = function () {
                    return {
                        [stateName]:stateData
                    }
                };
            }
            if(App["components"]){
                this.getComponent(App["components"],stateName,stateData)
            }
            return App;
    }
    getComponent(App,stateName,stateData) {
        Object.keys(App).forEach((key)=>{
            this.child(App,key,stateName,stateData);
        });
    }

   child(App,key,stateName,stateData) {
       // let that = this;
        if(App[key]["data"]){
            let data = App[key]["data"]();
            data[stateName] = stateData;
            App[key]["data"] = function () {
                return data
            };
            let Data = {
                ...App[key]["methods"]
            };
            Data['wx'] = function (){
                return {
                    getState:function getState(){
                        return this;
                    }
                };
            }
            console.log(Data)
            App[key]["methods"] = Data;
        }else {
            App[key]["data"] = function () {
                return {
                    [stateName]:stateData
                }
            };
        }
        if(App[key]["components"]){
            this.getComponent(App[key]["components"],stateName,stateData)
        }
    }
}